package org.flckphoto;

import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
 * Extends surface view class to allow us to preview camera
 */
class Preview extends SurfaceView implements SurfaceHolder.Callback{
	
	private static final String TAG = "Preview";
	private SurfaceHolder mainHolder;
	protected Camera camera;
	
	/**
	 * Object to setup preview screen for CameraManager on creation
	 * 
	 * @param context Interface to global information about an application environment. 

	 */
	Preview(Context context){
		super(context);
		
		//Makes it so we know when the surface needs to be destroyed or created
		mainHolder = getHolder();
		mainHolder.addCallback(this);
		mainHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	/**
	 * Create the surface by opening the camera and setting up the surface
	 * 
	 * @param holder Editor for the preview screen which is of type: surface
	 */
	@Override
	public void surfaceCreated(SurfaceHolder holder){
		Log.d(TAG, "onSurfaceCreated");
		try{
			camera = Camera.open();
			camera.setPreviewDisplay(holder);
			//Sets up our preview callback in order to show the Camera on screen
			camera.setPreviewCallback(new PreviewCallback() { 
		        // Called for every preview frame to be drawn on screen
		        public void onPreviewFrame(byte[] data, Camera camera) { 
		          Preview.this.invalidate(); 
		        }
		      });
		}catch (IOException e){
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 ****When the surface holder has been changed****
	 *
	 *@param holder Editor for the preview screen which is of type: surface
	 *@param format PixelFormat of the surface
	 *@param width Width of surface desired
	 *@param height Height of surface desired
	 */
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,int height){
		Log.d(TAG, "Camera preview starting...");
		camera.startPreview();
	}
	
	/**
	 ****When the surface is being order to be destroyed
	 *
	 *@param holder Editor for the preview screen which is of type: surface
	 */
	@Override
	public void surfaceDestroyed(SurfaceHolder holder){
		Log.d(TAG, "camera is being released...");
		camera.stopPreview();
		camera.setPreviewCallback(null);
		camera.setOneShotPreviewCallback(null);
		camera.release();
		camera = null;
	}

	

	

}
